package org.linzhu;

import java.util.Iterator;
import java.util.List;
import org.hibernate.Session;
import org.hibernate.Transaction;
import org.hibernate.stat.Statistics;

public class HelloWorld {

    public static void main(String[] args) {
        Session session;
        Transaction tx;
        Message message;
        
        // get statistics out of the Hibernate engine at runtime
        Statistics stats = HibernateUtil.getSessionFactory().getStatistics();
        stats.setStatisticsEnabled(true);

        // First unit of work
        session = HibernateUtil.getSessionFactory().openSession();
        tx = session.beginTransaction();
        message = new Message("Hello World");
        Long msgId = (Long) session.save(message);
        //tx.commit();
        //session.close();

        // Second unit of work
        //session = HibernateUtil.getSessionFactory().openSession();
        //tx = session.beginTransaction();
        List messages = session.createQuery("from Message m order by m.text asc").list();
        System.out.println(messages.size() + " message(s) found:");

        for (Iterator iter = messages.iterator(); iter.hasNext();) {
            Message loadedMsg = (Message) iter.next();
            System.out.println(loadedMsg.getId() + ": " + loadedMsg.getText());
        }
        //tx.commit();
        //session.close();

        // Third unit of work
        //session = HibernateUtil.getSessionFactory().openSession();
        //tx = session.beginTransaction();
        // msgId holds the identifier value of the first message
        message = (Message) session.get( Message.class, msgId );
        message.setText("Greetings Earthling");
        message.setNextMessage(new Message("Take me to your leader (please)"));
        //tx.commit();
        //session.close();

        // Fourth unit of work
        //session = HibernateUtil.getSessionFactory().openSession();
        //tx = session.beginTransaction();
        messages = session.createQuery("from Message m order by m.text asc").list();
        System.out.println(messages.size() + " message(s) found:");

        for (Iterator iter = messages.iterator(); iter.hasNext();) {
            Message loadedMsg = (Message) iter.next();
            System.out.println(loadedMsg.getId() + ": " + loadedMsg.getText());
        }
        tx.commit();
        session.close();

        stats.logSummary();
        
        // Shutting down the application
        HibernateUtil.shutdown();
    }
}